package com.lianxueda.drawing.controller;

import com.lianxueda.drawing.common.R;
import com.lianxueda.drawing.domain.dto.CheckingInRequest;
import com.lianxueda.drawing.domain.pojo.CheckingIn;
import com.lianxueda.drawing.service.CheckingInService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/checking")
@RequiredArgsConstructor
@Tag(name = "考勤管理模块", description = "考勤管理模块接口")
public class CheckingInController {

    private final CheckingInService checkingInService;


    //新增考勤管理
    @PostMapping("/save")
    @Operation(summary = "新增考勤")
    public R save(@RequestBody CheckingInRequest request) {
        List<Integer> statuses = request.getStatus();
        List<Integer> studentIds = request.getStudentId();
        Integer courseId = request.getCourseId();
        Integer schedelesId = request.getSchedelesId();

        // 校验数据合法性
        if (statuses.size() != studentIds.size()) {
            return R.fail("状态与学生ID数量不匹配");
        }

        // 创建 CheckingIn 对象列表
        List<CheckingIn> checkingInList = new ArrayList<>();
        for (int i = 0; i < studentIds.size(); i++) {
            CheckingIn checkingIn = new CheckingIn();
            checkingIn.setCourseId(courseId);
            checkingIn.setSchedelesId(schedelesId);
            checkingIn.setStudentId(studentIds.get(i));
            checkingIn.setState(statuses.get(i));
            checkingInList.add(checkingIn);
        }

//        for (Integer studentId : studentIds) {
//            boolean isRemoved = checkingInService.removeByCourseIdAndSchedelesId(courseId, schedelesId, studentId);
//            if (!isRemoved) {
//                return R.fail("删除旧记录失败，请重试");
//            }
//        }
        // 保存新的记录
        for (CheckingIn checkingIn : checkingInList) {
            boolean isSaved = checkingInService.save(checkingIn);
            if (!isSaved) {
                return R.fail("考勤数据提交失败，请重试");
            }
        }

        return R.suc("考勤数据提交成功");
    }


}
